package com.alex.monitor.starter.demo.service;

import cn.hutool.core.util.RandomUtil;
import com.alex.monitor.core.annotation.MethodMonitor;
import com.alex.monitor.core.enums.TriggerType;
import com.alex.monitor.starter.demo.ex.BusinessException;
import com.alex.monitor.starter.demo.ex.GlobalException;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import java.util.List;
import org.springframework.stereotype.Service;

/**
 * @author Alex.Liu
 * @date: 2025-02-17 12:59
 * @since 1.0.0
 */
@Service
public class FooService {

    private static final List<String> RESULT = Lists.newArrayList("foo", "bar", "baz");

    /**
     * 当方法返回foo的时候，发送预警信息
     *
     * @return
     */
    @MethodMonitor(trigger = TriggerType.RESULT, result = "foo")
    public String resultStrFoo() {
        return RandomUtil.randomEle(RESULT);
    }


    @MethodMonitor(trigger = TriggerType.RESULT, result = "foo", code = "error")
    public JSONObject resultJsonFoo() {
        JSONObject obj = new JSONObject();
        obj.put("error", RandomUtil.randomEle(RESULT));
        return obj;
    }


    /**
     * 测试抛出异常时预警
     *
     * @throws Exception
     */
    @MethodMonitor(trigger = TriggerType.EXCEPTION, exceptions = {Exception.class})
    public void exception() throws Exception {
        String random = RandomUtil.randomEle(RESULT);
        if (random.contains("foo")) {
            throw new Exception("异常监控测试");
        }
    }

    /**
     * 自定义异常预警测试
     *
     * @throws Exception
     */
    @MethodMonitor(trigger = TriggerType.EXCEPTION, exceptions = {GlobalException.class})
    public void customException() {
        String random = RandomUtil.randomEle(RESULT);
        if (random.contains("foo")) {
            throw new GlobalException();
        } else if (random.contains("bar")) {
            throw new BusinessException();
        }
    }
}